/**
 * ===========================================
 * Project: gamehistory-service
 * ===========================================
 * Package: com.cyou.gamehistory.service
 * 
 * Copyright (c) 2012, CYOU All Rights Reserved.
 * ===========================================
 */
package com.cyou.gamehistory.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.cyou.framework.cache.memcached.SpyMemcachedClient;
import com.cyou.framework.pagination.page.Page;
import com.cyou.framework.pagination.page.Pagination;
import com.cyou.framework.pagination.proxy.PaginationSupport;
import com.cyou.framework.util.DateUtility;
import com.cyou.framework.util.StringUtility;
import com.cyou.gamehistory.entity.GameHistoryFeed;
import com.cyou.gamehistory.entity.UserInfo;
import com.cyou.gamehistory.entity.vo.AppStat;
import com.cyou.gamehistory.repository.GameHistoryFeedDao;

/**
 * <p>GameHistoryFeedService</p>
 *
 * @since 1.0
 * @version 1.0 2012-12-11
 * @author zhangxingkai
 */
@Component
@Transactional(readOnly = true)
public class GameHistoryFeedService {
	
	private static final Logger logger = LoggerFactory.getLogger(GameHistoryFeedService.class);

	@Autowired
	private GameHistoryFeedDao gameHistoryFeedDao;

	@Autowired
	private SpyMemcachedClient spyMemcachedClient;
	
	@Transactional
	public void saveGameHistoryFeed(UserInfo userinfo,Double cost,Integer beginYear,Integer gameCount,String honor){
		logger.info("保存feed 开始。。。");
		GameHistoryFeed gameHistoryFeed=new GameHistoryFeed();
		gameHistoryFeed.setCost(cost);
		gameHistoryFeed.setCreateTime(new Date());
		@SuppressWarnings("deprecation")
		Integer nowYear=new Date().getYear()+1900;
		gameHistoryFeed.setGameAge(nowYear-beginYear+1);
		gameHistoryFeed.setGameBeginTime(beginYear);
		gameHistoryFeed.setGameCount(gameCount);
		gameHistoryFeed.setNickname(userinfo.getNickname());
		gameHistoryFeed.setUserId(userinfo.getUserId());
		gameHistoryFeed.setHonor(honor);
		gameHistoryFeed.setSmallImage(userinfo.getSmallImage());
		//获取memcache中  存入的feedList  用户首页10s刷新一次
		String key="gameHistoryFeed.pull.flag";
		List<GameHistoryFeed> list=spyMemcachedClient.get(key);
		int time=12*60*60;
		if(list==null){
			list=new LinkedList<GameHistoryFeed>();
			list.add(gameHistoryFeed);
			spyMemcachedClient.set(key, time, list);
		}else{
			list.add(gameHistoryFeed);
			spyMemcachedClient.set(key, time, list);
		}
		
		gameHistoryFeedDao.saveGameHistoryFeed(gameHistoryFeed);
		//清空首页所有动态页面的memcached缓存
		this.flushMem();
		
		logger.info("保存feed 结束");
	}

	public List<GameHistoryFeed> findAllFeeds(String nickname, Date createTime,
			Integer pageSize, Integer pageNo){
		Map<String, Object> map = new HashMap<String, Object>();

		Page page = new Pagination();
		page.setCurrentPage(pageNo);
		page.setPageSize(pageSize);

		map.put("page", page);
		map.put("nickname", nickname);
		map.put("createTime", createTime);
		return gameHistoryFeedDao.findAllFeeds(map);
	}
	/**
	 * 所有动态页面list
	 * @param nickname
	 * @param createTime
	 * @param pageSize
	 * @param pageNo
	 * @return
	 */
	public PaginationSupport<GameHistoryFeed> findAllFeeds2(String nickname,
			Integer createTime, Integer pageSize, Integer pageNo){
		Date dateTime=null;
		if(createTime.equals(0)){
			createTime=null;
		}else{
			dateTime=DateUtility.beforeDate(createTime);
		}
		String key=nickname+"."+createTime+".gamehistoryFeedList"+"."+pageNo.toString();
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		PaginationSupport<GameHistoryFeed> pageinationSupport = new PaginationSupport<GameHistoryFeed>();
		pageinationSupport.setCurrentPage(pageNo);
		pageinationSupport.setPageSize(pageSize);

		map.put("page", pageinationSupport);
		map.put("nickname", nickname);
		map.put("createTime", dateTime);
		
		PaginationSupport<GameHistoryFeed> gameHistoryFeedList=spyMemcachedClient.get(key);
		if(gameHistoryFeedList==null){
			gameHistoryFeedList=gameHistoryFeedDao.findAllFeeds2(map);
			spyMemcachedClient.set(key, 10*60, gameHistoryFeedList);
		}
		List<GameHistoryFeed> list=gameHistoryFeedList.getDatas();
		for(GameHistoryFeed feed:list){
			long cTime = feed.getCreateTime().getTime();
			long nowTime = new Date().getTime();
			int offset = (int) (((nowTime - cTime) / 1000) / 60);
			if (offset < 15 && offset>0 ) {
				feed.setMinute(offset);
			}
			if(offset ==0){
				feed.setMinute(1);
			}
		}
		return gameHistoryFeedList;
	}

	public List<GameHistoryFeed> getLastestFeeds(int limit) {
		String key="gamehistoryFeed.lastestFeed.8";
		List<GameHistoryFeed> feedList = spyMemcachedClient.get(key);
		if (feedList == null) {
			feedList=gameHistoryFeedDao.getLastestFeeds(limit);
			spyMemcachedClient.set(key, 30*60, feedList);
		}
				
		for (GameHistoryFeed feed : feedList) {
			long createTime = feed.getCreateTime().getTime();
			long nowTime = new Date().getTime();
			int offset = (int) (((nowTime - createTime) / 1000) / 60);
			if (offset < 15 && offset>0) {
				feed.setMinute(offset);
			}
			if (offset == 0) {
				feed.setMinute(1);
			}
		}
		return feedList;
	}
	/**
	 * 首页10s请求memcache是否有新的feed
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public List<GameHistoryFeed> pull() {
			String key="gameHistoryFeed.pull.flag";
			List<GameHistoryFeed> feedList = spyMemcachedClient.get(key);
			if(feedList==null){
				return null;
			}
			List<GameHistoryFeed> list=new ArrayList<GameHistoryFeed>();
			for(int i=feedList.size()-1;i>=0;i--){
				GameHistoryFeed feed=feedList.get(i);
				Date date=feed.getCreateTime();
				Date now=new Date();
				long offsetTime=(now.getTime()-date.getTime())/1000;
				if(offsetTime<10){
					int minute = date.getMinutes();
					int nowMinute = now.getMinutes();
					int oset = 1;
					if (nowMinute > minute) {
						oset = nowMinute - minute;
					}
					feed.setMinute(oset);
					list.add(feed);
				}else{
					break;
				}
			}
				
			return list;
	}
	/**
	 * 参加人数与使用人数统计   
	 * @param beginTime
	 * @param endTime
	 * @return
	 * @throws ParseException
	 */
	@SuppressWarnings("deprecation")
	public List<AppStat> getAppStat(String beginTime,String endTime) throws ParseException{
		
		if(StringUtility.isNotBlank(beginTime)){
			beginTime=beginTime+" 00:00:00";
		}else{
			Date date=new Date();
			GregorianCalendar gc =new GregorianCalendar();
			gc.setTime(date);
			gc.add(GregorianCalendar.MONTH, -2);
			gc.getTime();
			beginTime=new SimpleDateFormat("yyyy-MM-dd").format(gc.getTime())+" 00:00:00";
		}
		if(StringUtility.isNotBlank(endTime)){
			endTime=endTime+" 23:59:59";
		}else{
			Date date=new Date();
			GregorianCalendar gc =new GregorianCalendar();
			gc.setTime(date);
			gc.add(GregorianCalendar.MONTH, -1);
			endTime=new SimpleDateFormat("yyyy-MM-dd").format(gc.getTime())+" 23:59:59";
		}
		
		Date dateBegin=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginTime);
		Date dateEnd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
		
		Integer beginYear=dateBegin.getYear()+1900;
		Integer endYear=dateEnd.getYear()+1900;
		Integer beginMonth=dateBegin.getMonth()+1;
		Integer endMonth=(endYear-beginYear)*12+dateEnd.getMonth()+1;
		int length=endMonth-beginMonth+1;
		AppStat appStatUserCount=new AppStat();
		AppStat appStatUserTimes=new AppStat();
		Integer[] stat1=new Integer[length];
		Integer[] stat2=new Integer[length];
		for(Integer i=0;i<length;i++){
			Map<String,Integer> map=new HashMap<String, Integer>();
			if((beginMonth+i-12)>0){
				map.put("year", endYear);
				map.put("month", beginMonth+i-12);
			}else{
				map.put("year", beginYear);
				map.put("month", beginMonth+i);
			}
			Integer userCount=gameHistoryFeedDao.getMonthUserCount(map);
			Integer userTimes=gameHistoryFeedDao.getMonthUserTimes(map);
			stat1[i]=userCount;
			stat2[i]=userTimes;
			
		}
		appStatUserCount.setName("参加人数");
		appStatUserCount.setData(stat1);
		appStatUserTimes.setName("使用应用人次");
		appStatUserTimes.setData(stat2);
		List<AppStat> list=new ArrayList<AppStat>();
		list.add(appStatUserCount);
		list.add(appStatUserTimes);
		return list;
		
	}
	
	/**
	 * 清除   所有动态页 首页  第一页 缓存
	 */
	public void flushMem(){
		String feedKey="null.null.gamehistoryFeedList.1";
		String indexKey="gamehistoryFeed.lastestFeed.8";
		String timeFeedKey1="null.60000.gamehistoryFeedList.1";
		String timeFeedKey2="null.600000.gamehistoryFeedList.1";
		String timeFeedKey3="null.1800000.gamehistoryFeedList.1";
		String timeFeedKey4="null.3600000.gamehistoryFeedList.1";
		String timeFeedKey5="null.7200000.gamehistoryFeedList.1";
		String timeFeedKey6="null.14400000.gamehistoryFeedList.1";
		
		spyMemcachedClient.delete(feedKey);
		spyMemcachedClient.delete(indexKey);
		spyMemcachedClient.delete(timeFeedKey1);
		spyMemcachedClient.delete(timeFeedKey2);
		spyMemcachedClient.delete(timeFeedKey3);
		spyMemcachedClient.delete(timeFeedKey4);
		spyMemcachedClient.delete(timeFeedKey5);
		spyMemcachedClient.delete(timeFeedKey6);
		
	}
	
	
	
}
